//
//  DTagDropViewController.swift
//  Drop
//
//  Created by hushaohua on 2018/2/26.
//  Copyright © 2018年 init. All rights reserved.
//

import UIKit
import CoreData

class DDropSegment{
    var drop:Drop?;//
    var closeToNext:Bool = false;
}

class DTagDropViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var beginDate:Date?;
    var endDate:Date?;
    var tag:Tag?;
    
    //MARK: - init
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil);
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:- life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.white;
        self.configTableView();
        self.configNavigationItem();
        self.configDropsController();
        self.requestNewest();
    }
    
    //MARK: - tableView
    func configTableView() -> Void{
        self.tableView.rowHeight = 86;
        self.tableView.separatorStyle = .none;
        self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 84, right: 0);
        self.tableView.register(DDropSegmentTableViewCell.self, forCellReuseIdentifier: DDropSegmentTableViewCell.normalReuseId);
        self.tableView.register(DDropSegmentTableViewCell.self, forCellReuseIdentifier: DDropSegmentTableViewCell.closeNextReuseId);
        self.tableView.register(DDropTrailTableViewCell.self, forCellReuseIdentifier: "trail");
        self.tableView.register(DDropLineHeaderView.self, forHeaderFooterViewReuseIdentifier: "Header");
        self.view.addSubview(self.tableView);
    }
    
    lazy var tableView:UITableView = {
        var tableView:UITableView = UITableView(frame: self.view.bounds, style: .plain);
        tableView.delegate = self;
        tableView.dataSource = self;
        return tableView;
    }();
    
    //MARK:- drops controller
    func configDropsController() -> Void {
//        self.dropsController.delegate = self;
    }
    
    @objc func currentDayDidChanged(_ notification:Notification) -> Void{
        self.requestNewest();
    }
    
    lazy var dropSegments:[[DDropSegment]] = {
        var drops:[[DDropSegment]] = [[DDropSegment]]();
        return drops;
    }();
    func requestNewest() -> Void{
        do{
            self.configDropsPredicate();
            self.dropSegments.removeAll();
            try self.dropsController.performFetch()
            if (self.dropsController.sections != nil){
                for section in self.dropsController.sections! {
                    var dropSegs:[DDropSegment] = [DDropSegment]();
                    
                    for index in 0..<section.numberOfObjects {
                        let drop = section.objects![index] as! Drop;
                        let dropSeg:DDropSegment = DDropSegment();
                        dropSeg.drop = drop;
                        dropSegs.append(dropSeg);
                        if (index < section.numberOfObjects - 1){
                            let nextDrop = section.objects![index + 1] as! Drop;
                            if (drop.begin!.isEqual(to: nextDrop.end! as Date)){
                                dropSeg.closeToNext = true;
                            }else{
                                let trailSeg:DDropSegment = DDropSegment();
                                dropSegs.append(trailSeg);
                            }
                        }
                    }
                    self.dropSegments.append(dropSegs);
                }
            }
            
            self.tableView.reloadData();
        }catch{
            let nserror = error as NSError
            fatalError("tags controller fetch error \(nserror), \(nserror.userInfo)")
        }
    }
    
    func configDropsPredicate() -> Void{
        var predicate:NSPredicate? = nil;
        if (self.tag != nil){
            if (self.beginDate != nil && self.endDate != nil){
                predicate = NSPredicate(format: "(tag == %@ AND begin >= %@ AND begin <= %@)", self.tag!, self.beginDate! as NSDate, self.endDate! as NSDate);
            }else{
                predicate = NSPredicate(format: "(tag == %@)", self.tag!);
            }
        }
        self.dropsController.fetchRequest.predicate = predicate;
    }
    
    //MARK:- NSFetchedResultsController
    lazy var dropsController:NSFetchedResultsController<Drop> = {
        let request:NSFetchRequest = Drop.defaultFetchRequest();
        request.sortDescriptors = [NSSortDescriptor(key: "begin", ascending: false)];
        request.propertiesToFetch = ["begin", "end"];
        request.includesSubentities = false;
        
        var controller:NSFetchedResultsController<Drop> = NSFetchedResultsController(fetchRequest: request, managedObjectContext: HStoreManager.defaultManger().context, sectionNameKeyPath: "dateString", cacheName: nil);
        return controller;
    }();
    
    //MARK:- tableView
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let dropSeg = self.dropSegments[indexPath.section][indexPath.row];
        return dropSeg.drop != nil ? (dropSeg.closeToNext ? 54 : 64) : 34;
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dropSegments.count;
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dropSegments[section].count;
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view:DDropLineHeaderView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "Header") as! DDropLineHeaderView;
        view.contentView.backgroundColor = UIColor.clear;
        view.timeLabel.text = self.dropsController.sections![section].name;
        return view;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dropSeg = self.dropSegments[indexPath.section][indexPath.row];
        if (dropSeg.drop != nil){
            let reuseId = dropSeg.closeToNext ? DDropSegmentTableViewCell.closeNextReuseId : DDropSegmentTableViewCell.normalReuseId;
            let cell:DDropSegmentTableViewCell = tableView.dequeueReusableCell(withIdentifier: reuseId, for: indexPath) as! DDropSegmentTableViewCell;
            cell.selectionStyle = .none;
            if (!dropSeg.closeToNext){
                cell.beginDateLabel?.text = (dropSeg.drop!.begin! as Date).minuteTimeString();
            }
            cell.endDateLabel?.text = (dropSeg.drop!.end! as Date).minuteTimeString();
            var durationString:String = "";
            let interval:Int = Int(dropSeg.drop!.end!.timeIntervalSince(dropSeg.drop!.begin! as Date));
            if (interval < 60){
                durationString = "1'";
            }else if (interval < 3600){
                durationString = "\(interval / 60)'";
            }else{
                durationString = "\(interval / 3600):\((interval % 3600)/60)'";
            }
            cell.durationLabel.text = "\(durationString)";
            return cell;
        }else{
            let cell:DDropTrailTableViewCell = tableView.dequeueReusableCell(withIdentifier: "trail", for: indexPath) as! DDropTrailTableViewCell;
            return cell;
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 22;
    }
    
    func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
        return true;
    }
    
    func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
        return true;
    }
    
    func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
        
    }
    
    //MARK: - navigation
    func configNavigationItem() -> Void{
        self.navigationItem.titleView = self.titleView();
        let calendar = Calendar.current;
        if (self.beginDate != nil && self.endDate != nil){
            if (calendar.isDate(self.beginDate!, inSameDayAs: self.endDate!)){
                self.subTitleLabel.text = "\(self.beginDate!.defaultDateString())";
            }else{
                self.subTitleLabel.text = "\(self.beginDate!.defaultDateString())->\(self.endDate!.defaultDateString())";
            }
        }
    }
    
    func titleView() -> UIView{
        let view = UIView(frame: CGRect(x:0,y:0,width:200,height:44));
        view.addSubview(self.titleLabel());
        view.addSubview(self.subTitleLabel);
        return view;
    }
    
    func titleLabel() -> UILabel{
        let label:UILabel = UILabel(frame: CGRect(x:0,y:6,width:200,height:24));
        label.autoresizingMask = [.flexibleWidth];
        label.text = self.tag?.name;
        label.font = UIFont.systemFont(ofSize: 18);
        label.textAlignment = .center;
        label.textColor = UIColor.black;
        return label;
    }
    
    lazy var subTitleLabel:UILabel = {
        var label:UILabel = UILabel(frame: CGRect(x:0,y:30,width:200,height:12));
        label.autoresizingMask = [.flexibleWidth];
        label.text = "全部";
        label.font = UIFont.systemFont(ofSize: 10, weight: .light);
        label.textAlignment = .center;
        label.textColor = UIColor.gray;
        return label;
    }();
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
